package capricornus.components.utils.displayneartips
{
	import capricornus.components.utils.fadeaway.FadeAwayController;
	
	import fl.transitions.TweenEvent;
	
	import flash.display.DisplayObject;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.TimerEvent;
	import flash.utils.Timer;
	import flash.utils.getTimer;
	import flash.utils.setTimeout;
	
	internal class DisplayNearItem extends Sprite
	{
		private var fade:FadeAwayController;
		
		private var _beginTime:uint;
		private var _timer:Timer;
		private var _hasHide:Boolean = false;
		
		public function DisplayNearItem( displayTime:Number=5 )
		{
			super();
			init( displayTime );
		}
		
		private function init( displayTime:Number ):void
		{
			_beginTime = getTimer();
			
			_timer = new Timer( displayTime*1000, 1 );
			_timer.addEventListener( TimerEvent.TIMER, onTimer, false, 0, true );
		}
		
		public function destroy():void
		{
			onMotionFinish( null );
		}
		
		private function onTimer( e:TimerEvent ):void
		{
			hide();
		}
		
		public function addItem( dis:DisplayObject ):void
		{
			addChild( dis );
			
			if( !_timer.running ) _timer.start();
		}
		
		public function hideNow():void
		{
			if( _hasHide ) return;
			
			var t:uint = getTimer() - _beginTime;
			if( t > 1000 )
			{
				if( _timer.running ) 
				{
					_timer.stop();
					hide();
				}
			}
			else
			{
				_hasHide = true;
				
				_timer.delay = 1000 - t;
				_timer.reset();
				_timer.start();
			}
		}
		
		private function hide():void
		{
			_hasHide = true;
			
			fade = new FadeAwayController( 1, false );
			fade.fade( this, false );
			fade.addEventListener( TweenEvent.MOTION_FINISH, onMotionFinish, false, 0, true );
		}
		
		private function onMotionFinish( e:Event ):void
		{
			if( _timer != null )
			{
				_timer.removeEventListener( TimerEvent.TIMER, onTimer );
				if( _timer.running )
				{
					_timer.stop();
				}
				_timer = null;
			}
			
			if( fade != null)
			{
				fade.destroy();
				fade = null;
			}
			
			this.dispatchEvent( new DisplayNearEvent( DisplayNearEvent.HIDE ) );
		}
	}
}